package service

import (
	"errors"
	"we-account-api/model"
	"we-account-api/pkg/database"
	"we-account-api/pkg/jwt"
	"we-account-api/pkg/request"
)

// UserService 提供用户相关的服务
// Register 注册新用户
// Login 用户登录
// GetUserInfo 获取用户信息
// GetUserList 获取用户列表

type userService struct{}

var UserService = new(userService)

func (s *userService) Register(req request.RegisterRequest) error {
	var count int64
	database.DB.Model(&model.User{}).Where("username = ?", req.Username).Count(&count)
	if count > 0 {
		return errors.New("用户名已存在")
	}

	user := &model.User{
		Username: req.Username,
		Password: req.Password, // 实际使用时需要对密码进行加密
		Email:    req.Email,
	}

	return database.DB.Create(user).Error
}

func (s *userService) Login(req request.LoginRequest) (string, error) {
	var user model.User
	err := database.DB.Where("username = ?", req.Username).First(&user).Error
	if err != nil {
		return "", errors.New("用户不存在")
	}

	if user.Password != req.Password { // 实际使用时需要对密码进行验证
		return "", errors.New("密码错误")
	}

	// 生成JWT token
	token, err := jwt.GenerateToken(user.ID)
	if err != nil {
		return "", errors.New("生成token失败")
	}

	return token, nil
}

func (s *userService) GetUserInfo(userId int64) (model.User, error) {
	var user model.User
	err := database.DB.Where("id = ?", userId).First(&user).Error
	if err != nil {
		return model.User{}, errors.New("用户不存在")
	}
	return user, nil
}

func (s *userService) GetUserList(page, pageSize int) (users []model.User, total int64, err error) {
	offset := (page - 1) * pageSize
	err = database.DB.Model(&model.User{}).
		Count(&total).
		Offset(offset).
		Limit(pageSize).
		Find(&users).Error
	return
}

func (s *userService) FindOrCreate(user *model.User) error {
	result := database.DB.Where("open_id = ?", user.OpenID).FirstOrCreate(user)
	return result.Error
}
